import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

import '../services/providers/tunnel_provider_compat.dart';

/// 添加服务对话框
class AddServiceDialog extends StatefulWidget {
  const AddServiceDialog({super.key});

  @override
  State<AddServiceDialog> createState() => _AddServiceDialogState();
}

class _AddServiceDialogState extends State<AddServiceDialog> {
  final _formKey = GlobalKey<FormState>();
  final _serviceNameController = TextEditingController();
  final _localHostController = TextEditingController(text: 'localhost');
  final _localPortController = TextEditingController();

  bool _isLoading = false;
  String _selectedProtocol = 'http'; // 默认选择HTTP

  @override
  void dispose() {
    _serviceNameController.dispose();
    _localHostController.dispose();
    _localPortController.dispose();
    super.dispose();
  }

  Future<void> _createTunnel() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() => _isLoading = true);

    try {
      final tunnelProvider = Provider.of<TunnelProvider>(context, listen: false);
      
      final success = await tunnelProvider.createTunnel(
        serverName: _serviceNameController.text.trim(),
        localHost: _localHostController.text.trim(),
        localPort: _localPortController.text.trim(),
        tunnelType: _selectedProtocol,
      );

      if (success && mounted) {
        Navigator.of(context).pop(true);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('隧道创建成功！'),
            backgroundColor: Colors.green,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('创建失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Container(
        width: 400,
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 标题
            Row(
              children: [
                const Icon(
                  Icons.add_circle_outline,
                  color: Color(0xFF007AFF),
                  size: 28,
                ),
                const SizedBox(width: 12),
                Text(
                  '添加服务',
                  style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                IconButton(
                  onPressed: () => Navigator.of(context).pop(),
                  icon: const Icon(Icons.close),
                ),
              ],
            ),
            const SizedBox(height: 24),

            // 表单
            Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  // 服务名称
                  TextFormField(
                    controller: _serviceNameController,
                    decoration: InputDecoration(
                      labelText: '服务名称',
                      hintText: '例如：我的网站服务 或 my-web-service',
                      hintStyle: TextStyle(
                        color: Theme.of(context).hintColor.withValues(alpha: 0.4),
                        fontSize: 14,
                      ),
                      prefixIcon: const Icon(Icons.label_outline),
                      border: const OutlineInputBorder(),
                    ),
                    validator: (value) {
                      if (value == null || value.trim().isEmpty) {
                        return '请输入服务名称';
                      }
                      // 支持中文、字母、数字、横线和下划线
                      if (!RegExp(r'^[\u4e00-\u9fa5a-zA-Z0-9\-_\s]+$').hasMatch(value.trim())) {
                        return '服务名称只能包含中文、字母、数字、横线、下划线和空格';
                      }
                      return null;
                    },
                  ),
                  const SizedBox(height: 16),

                  // 本地主机
                  TextFormField(
                    controller: _localHostController,
                    decoration: InputDecoration(
                      labelText: '本地主机',
                      hintText: 'localhost',
                      hintStyle: TextStyle(
                        color: Theme.of(context).hintColor.withValues(alpha: 0.4),
                        fontSize: 14,
                      ),
                      prefixIcon: const Icon(Icons.computer),
                      border: const OutlineInputBorder(),
                    ),
                    validator: (value) {
                      if (value == null || value.trim().isEmpty) {
                        return '请输入本地主机地址';
                      }
                      return null;
                    },
                  ),
                  const SizedBox(height: 16),

                  // 本地端口
                  TextFormField(
                    controller: _localPortController,
                    decoration: InputDecoration(
                      labelText: '本地端口',
                      hintText: '3000',
                      hintStyle: TextStyle(
                        color: Theme.of(context).hintColor.withValues(alpha: 0.4),
                        fontSize: 14,
                      ),
                      prefixIcon: const Icon(Icons.settings_input_component),
                      border: const OutlineInputBorder(),
                    ),
                    keyboardType: TextInputType.number,
                    inputFormatters: [
                      FilteringTextInputFormatter.digitsOnly,
                      LengthLimitingTextInputFormatter(5),
                    ],
                    validator: (value) {
                      if (value == null || value.trim().isEmpty) {
                        return '请输入本地端口';
                      }
                      final port = int.tryParse(value.trim());
                      if (port == null || port < 1 || port > 65535) {
                        return '端口必须在1-65535之间';
                      }
                      return null;
                    },
                  ),
                  const SizedBox(height: 16),

                  // 协议类型选择
                  DropdownButtonFormField<String>(
                    value: _selectedProtocol,
                    decoration: const InputDecoration(
                      labelText: '协议类型',
                      prefixIcon: Icon(Icons.public),
                      border: OutlineInputBorder(),
                    ),
                    items: const [
                      DropdownMenuItem(
                        value: 'http',
                        child: Row(
                          children: [
                            Icon(Icons.http, size: 20),
                            SizedBox(width: 8),
                            Text('HTTP'),
                          ],
                        ),
                      ),
                      DropdownMenuItem(
                        value: 'tcp',
                        child: Row(
                          children: [
                            Icon(Icons.settings_ethernet, size: 20),
                            SizedBox(width: 8),
                            Text('TCP'),
                          ],
                        ),
                      ),
                    ],
                    onChanged: (value) {
                      if (value != null) {
                        setState(() {
                          _selectedProtocol = value;
                        });
                      }
                    },
                  ),
                  const SizedBox(height: 24),

                  // 说明文字
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.blue.withValues(alpha: 0.1),
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(color: Colors.blue.withValues(alpha: 0.3)),
                    ),
                    child: const Text(
                      '创建隧道后，系统会为您分配一个公网地址，您可以通过这个地址访问本地服务。',
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.blue,
                      ),
                    ),
                  ),
                  const SizedBox(height: 24),

                  // 按钮
                  Row(
                    children: [
                      Expanded(
                        child: OutlinedButton(
                          onPressed: _isLoading ? null : () => Navigator.of(context).pop(),
                          child: const Text('取消'),
                        ),
                      ),
                      const SizedBox(width: 16),
                      Expanded(
                        child: ElevatedButton(
                          onPressed: _isLoading ? null : _createTunnel,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: const Color(0xFF007AFF),
                            foregroundColor: Colors.white,
                          ),
                          child: _isLoading
                              ? const SizedBox(
                                  width: 16,
                                  height: 16,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                                  ),
                                )
                              : const Text('创建'),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
